package start

import (
	"fmt"
	"github.com/gorilla/mux"
	"log"
	"net/http"
	"src/config"
	"src/service"
)

type RouterMod struct {
	Name     string
	Path     string
	Params   map[string]any
	OnBefore []func(*service.Req)
	Run      func(*service.Req)
	OnAfter  []func(*service.Req)
	Req      *service.Req
}

// http 路由逻辑
type Router struct {
	GroupName string
	RouterMod
}
type RouterGroup struct {
	Routers []*Router
	RouterMod
}

func (this *RouterGroup) AddGroup(routerGroup *RouterGroup) *RouterGroup {

	if routerGroup.Routers != nil {
		//if this.Routers != nil {
		//
		//	this.Routers = append(this.Routers, routerGroup.Routers...)
		//} else {
		//	this.Routers = routerGroup.Routers
		//}
		for _, v := range routerGroup.Routers {
			v.Path = this.Path + v.Path
			//log.Println(v.Path)
			v.GroupName = this.Name + "-" + routerGroup.Name
			//log.Println(this.Path)
			//if this.Name != "" {
			//	if this.Name != "" {
			//		v.GroupName = this.Name + "-" + routerGroup.Name
			//
			//	} else {
			//		v.GroupName = this.Name + "-" + routerGroup.Name
			//	}
			//
			//}
			//if this.Params != nil {
			//	if routerGroup.Params != nil {
			//		for k, v := range this.Params {
			//			if routerGroup.Params[k] != nil {
			//				routerGroup.Params[k] = v
			//			}
			//		}
			//	} else {
			//		routerGroup.Params = this.Params
			//	}
			//}
			this.Routers = append(this.Routers, v)
		}
	}
	return this
}
func (this *RouterGroup) Add(router *Router) *RouterGroup {
	router.Path = this.Path + router.Path
	this.Routers = append(this.Routers, router)
	return this
}
func (this *RouterGroup) Reg(http *mux.Router) *RouterGroup {
	for _, router := range this.Routers {
		router.GroupName = this.Name
		//router.Path = this.Path + router.Path
		log.Println(this.Name + ":" + router.Name + ":" + router.Path)
		if this.Params != nil {

			if this.Params != nil {
				for k, v := range this.Params {
					router.Params[k] = v
				}
			} else {
				router.Params = this.Params
			}
		}
		if this.Run != nil {
			if router.Run == nil {

				router.Run = this.Run
			}
		}
		if this.OnBefore != nil {

			if router.OnBefore != nil {
				router.OnBefore = append(this.OnBefore, router.OnBefore...)
			} else {
				router.OnBefore = this.OnBefore
			}
		}
		if this.OnAfter != nil {
			if router.OnAfter != nil {
				router.OnAfter = append(this.OnAfter, router.OnAfter...)
			} else {
				router.OnAfter = this.OnAfter
			}
		}
		if this.Req != nil {
			router.Req = this.Req
			if router.Req == nil {
				router.Req = this.Req
			}
		}
		router.Reg(http)
	}
	return this
}

//type ErrorResponse struct {
//	Error string `json:"error"`
//}

// 注册路由
func (this *Router) Reg(http1 *mux.Router) {
	//contextPath := config.V().GetString("server.http.servlet.context-path")
	contextPath := ""
	log.Println(this.Path)
	http1.HandleFunc(contextPath+this.Path, func(w http.ResponseWriter, r *http.Request) {
		// 使用中间件处理next(w, r)可能发生的错误
		defer func() {
			defer log.Println("请求结束")
			if err := recover(); err != nil && err != 0 {
				log.Printf("Recovered from panic: %v", err)
				w.Header().Set("Content-Type", "application/json")
				w.WriteHeader(http.StatusInternalServerError)
				_, err = fmt.Fprint(w, err)
				if err != nil {
					return
				}
				//_ = json.NewEncoder(w).Encode(ErrorResponse{Error: "Internal server error"})
			}
		}()
		//http1.ServeHTTP(w, r)
		//defer func() {
		//	log.Println("start.Reg 退出")
		//}()
		serverStop := config.V().GetBool("server-close.close")
		if serverStop {
			log.Println("服务器关闭中，当前请求被拦截 start.Reg")
			return
		}
		req := service.New(w, r)
		req.RouterParams = this.Params
		req.RouterPath = this.Path

		if this.OnBefore != nil {
			//log.Println("正在执行方法 start.OnBefore")
			for _, runBefore := range this.OnBefore {
				req.Next(runBefore)
			}
		}
		if this.Run != nil {
			//log.Println("正在执行方法 start.Run")
			req.Next(this.Run)
		}

		if this.OnAfter != nil {
			//req.Close = false
			//log.Println("正在执行方法 start.OnAfter")
			for _, runAfter := range this.OnAfter {
				req.Next(runAfter)
			}
		}
		log.Println("新的http请求进入 正在执行方法 start.Reg------------")

	})
}
